package com.sy.simpleegg.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.sy.simpleegg.bean.SupplementOrderBean
import com.sy.simpleegg.databinding.ItemSupplementOrderBinding
import com.sy.simpleegg.ext.logFile
import com.sy.simpleegg.ext.onClick

class SupplementOrderAdapter(
    private var supplementOrderList: MutableList<SupplementOrderBean>,
    private var listener: OnOutClickListener
) :
    RecyclerView.Adapter<SupplementOrderAdapter.GoodHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GoodHolder {
        val binding = ItemSupplementOrderBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return GoodHolder(binding)
    }

    override fun getItemCount(): Int = supplementOrderList.size ?: 0

    override fun onBindViewHolder(holder: GoodHolder, position: Int) {
        try {
            supplementOrderList.let {
                val order = it[position]
                holder.time.text = order.time
                holder.orderAmount.text = "${order.orderAmount.toLong()/100}"
                holder.orderCoins.text = "${order.orderCoins.toLong()}"
                holder.realCoins.text = "${order.realCoins.toLong()}"
                holder.btnOut.onClick {
                    listener.onOutCoins(order.id, position, order.time.replace("-", "").replace(":", "").trim(), order.orderCoins.toLong() - order.realCoins.toLong())
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            logFile("${javaClass.simpleName} 订单记录数据处理异常：${e.message}")
        }
    }

    fun refreshData(newList: MutableList<SupplementOrderBean>){
        supplementOrderList = newList
        notifyDataSetChanged()
    }

    fun refreshItem(position: Int, remainQuantity: Long){

    }

    interface OnOutClickListener{
        fun onOutCoins(id: Long, position: Int, flag: String, outQuantity: Long)
    }

    inner class GoodHolder(binding: ItemSupplementOrderBinding) :
        RecyclerView.ViewHolder(binding.root) {
        var time: TextView = binding.tvTime
        var orderAmount: TextView = binding.tvOrderAmount
        var orderCoins: TextView = binding.tvOrderCoins
        var realCoins: TextView = binding.tvRealCoins
        var btnOut: TextView = binding.btnOut
    }

}
